// 多页面多配置

const merge = require('webpack-merge')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpack = require('clean-webpack-plugin')
const ExtractTextWebpack = require('extract-text-webpack-plugin')
const path = require('path')

const baseConfig = {
  mode: 'production',
  entry: {
    react: 'react',
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].[chunkhash].js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextWebpack.extract({
          fallback: 'style-loader',
          use: 'css-loader'
        })
      }
    ]
  },
  plugins: [
    new ExtractTextWebpack({
      filename: 'css/[name].[chunkhash].css'
    }),
    new CleanWebpack(path.resolve(__dirname, 'dist'))
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          priority: 10,
          name: 'vendor',
          chunks: "all",
          minChunks: Infinity // 这里取值必须是Infinity,表示只会打vendow对应的包，不会打其他的代码
        }
      }
    },
    // 提取 webpack runtime
    runtimeChunk: {
      "name": "manifest"
    }
  }
}

const generatePage = function({
  title = '',
  entry = '',
  template = './src/index.html',
  name = '',
  chunks = []
} = {}) {
  return {
    entry,
    plugins: [
      new HtmlWebpackPlugin({
        chunks,
        template,
        title,
        filename: name + '.html'
      })
    ]
  }
}

const pages = [
  generatePage({
    title: 'page A',
    entry: {
      a: './src/pages/a'
    },
    name: 'a',
    chunks: ['react', 'a']
  }),
  generatePage({
    title: 'page B',
    entry: {
      b: './src/pages/b'
    },
    name: 'b',
    chunks: ['react', 'b']
  }),
  generatePage({
    title: 'page C',
    entry: {
      c: './src/pages/c'
    },
    name: 'c',
    chunks: ['react', 'c']
  }),
]

// console.log(pages.map(page => merge(baseConfig, page)))
module.exports = pages.map( page => merge(baseConfig, page))

// 安装parallel-webpack
// 命令行执行 node_modules/parallel-webpack/bin/run.js